import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class SiteGroupService extends BaseService<any> {
  private readonly logger = new Logger(SiteGroupService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getPage
   * 对应 PHP: SiteGroupService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(where: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';         $search_model = $this->model->withSearch([ 'keywords' ], $w...
const field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';
        const search_model = this.model.withSearch([ 'keywords' ), where).field(field).append([ 'app_name','app_list', 'addon_name','addon_list' )).order('create_time desc'];
        const list = this.pageQuery(search_model);
        return list;
    }

    /**
     * 获取所有分组
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getAll()
    {
        const field = 'group_id, group_name, group_desc, create_time, update_time, app';
        return this.model.field(field).order('create_time desc').select().toArray(];
    }

    /**
     * 分组详情
     * @param int group_id
     * @return */
    async getInfo(int group_id)
    {
        const field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';
        return this.model.where([ [ 'group_id', '=', group_id ) )).field(field).findOrEmpty().toArray(];

    }

    /**
     * 添加站点分组
     * @param data
     * @return mixed
     */
    async add(data)
    {
        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        const res = this.model.create(data);
        return res.group_id;
    }

    /**
     * 修改站点分组
     * @param int group_id
     * @param data
     * @return true
     */
    async edit(int group_id, data)
    {
        const group = this.model.where([ [ 'group_id', '=', group_id ) )).findOrEmpty().toArray(];

        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        this.model.update(data, [ [ 'group_id', '=', group_id ) )];
        //删除缓存
        const cache_name = self.cache_name . group_id;
        Cache.delete(cache_name);

        const site_list = ( this.siteService ).field('site_id,initalled_addon').where([ [ 'group_id', '=', group_id ) )).select().toArray(];
        if (!!site_list)) {
            sort(data[ 'app' )];
            sort(group[ 'app' )];
            sort(data[ 'addon' )];
            sort(group[ 'addon' )];

            if (json_encode(data[ 'app' )) != json_encode(group[ 'app' )) || json_encode(data[ 'addon' )) != json_encode(group[ 'addon' ))) {
                foreach (site_list as site) {
                    this.siteAddonsChange(site, group, data);
                    Cache.tag(CoreSiteService.cache_tag_name . site[ 'site_id' )).clear(];

                    // 更新微页面数据
                    const diy_service = this.diyService;
                    diy_service.loadDiyData([ site_id: site[ 'site_id' ], main_app: data[ 'app' ), tag: 'update' );
  }
  }

  /**
   * getAll
   * 对应 PHP: SiteGroupService_admin::getAll()
   * 逻辑类型: undefined - undefined
   */
  async getAll() {
    // 基于PHP真实逻辑: getAll
    // PHP原文: $field = 'group_id, group_name, group_desc, create_time, update_time, app';         return $this->model->field($field)->order('create_time desc')->sel...
const field = 'group_id, group_name, group_desc, create_time, update_time, app';
        return this.model.field(field).order('create_time desc').select().toArray(];
    }

    /**
     * 分组详情
     * @param int group_id
     * @return */
    async getInfo(int group_id)
    {
        const field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';
        return this.model.where([ [ 'group_id', '=', group_id ) )).field(field).findOrEmpty().toArray(];

    }

    /**
     * 添加站点分组
     * @param data
     * @return mixed
     */
    async add(data)
    {
        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        const res = this.model.create(data);
        return res.group_id;
    }

    /**
     * 修改站点分组
     * @param int group_id
     * @param data
     * @return true
     */
    async edit(int group_id, data)
    {
        const group = this.model.where([ [ 'group_id', '=', group_id ) )).findOrEmpty().toArray(];

        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        this.model.update(data, [ [ 'group_id', '=', group_id ) )];
        //删除缓存
        const cache_name = self.cache_name . group_id;
        Cache.delete(cache_name);

        const site_list = ( this.siteService ).field('site_id,initalled_addon').where([ [ 'group_id', '=', group_id ) )).select().toArray(];
        if (!!site_list)) {
            sort(data[ 'app' )];
            sort(group[ 'app' )];
            sort(data[ 'addon' )];
            sort(group[ 'addon' )];

            if (json_encode(data[ 'app' )) != json_encode(group[ 'app' )) || json_encode(data[ 'addon' )) != json_encode(group[ 'addon' ))) {
                foreach (site_list as site) {
                    this.siteAddonsChange(site, group, data);
                    Cache.tag(CoreSiteService.cache_tag_name . site[ 'site_id' )).clear(];

                    // 更新微页面数据
                    const diy_service = this.diyService;
                    diy_service.loadDiyData([ site_id: site[ 'site_id' ], main_app: data[ 'app' ), tag: 'update' );
  }
  }

  /**
   * getInfo
   * 对应 PHP: SiteGroupService_admin::getInfo()
   * 逻辑类型: undefined - undefined
   */
  async getInfo(group_id: number) {
    // 基于PHP真实逻辑: getInfo
    // PHP原文: $field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';         return $this->model->where([ [ 'group_id', '=', $group_id ]...
const field = 'group_id, group_name, group_desc, app, addon, create_time, update_time';
        return this.model.where([ [ 'group_id', '=', group_id ) )).field(field).findOrEmpty().toArray(];

    }

    /**
     * 添加站点分组
     * @param data
     * @return mixed
     */
    async add(data)
    {
        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        const res = this.model.create(data);
        return res.group_id;
    }

    /**
     * 修改站点分组
     * @param int group_id
     * @param data
     * @return true
     */
    async edit(int group_id, data)
    {
        const group = this.model.where([ [ 'group_id', '=', group_id ) )).findOrEmpty().toArray(];

        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        this.model.update(data, [ [ 'group_id', '=', group_id ) )];
        //删除缓存
        const cache_name = self.cache_name . group_id;
        Cache.delete(cache_name);

        const site_list = ( this.siteService ).field('site_id,initalled_addon').where([ [ 'group_id', '=', group_id ) )).select().toArray(];
        if (!!site_list)) {
            sort(data[ 'app' )];
            sort(group[ 'app' )];
            sort(data[ 'addon' )];
            sort(group[ 'addon' )];

            if (json_encode(data[ 'app' )) != json_encode(group[ 'app' )) || json_encode(data[ 'addon' )) != json_encode(group[ 'addon' ))) {
                foreach (site_list as site) {
                    this.siteAddonsChange(site, group, data);
                    Cache.tag(CoreSiteService.cache_tag_name . site[ 'site_id' )).clear(];

                    // 更新微页面数据
                    const diy_service = this.diyService;
                    diy_service.loadDiyData([ site_id: site[ 'site_id' ], main_app: data[ 'app' ), tag: 'update' );
  }
  }

  /**
   * add
   * 对应 PHP: SiteGroupService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: //判断应用是否全部是有效的已安装应用         $this->checkAddon(array_merge($data[ 'app' ], $data[ 'addon' ]));         $res = $this->model->create($data);         retu...
//判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        const res = this.model.create(data);
        return res.group_id;
    }

    /**
     * 修改站点分组
     * @param int group_id
     * @param data
     * @return true
     */
    async edit(int group_id, data)
    {
        const group = this.model.where([ [ 'group_id', '=', group_id ) )).findOrEmpty().toArray(];

        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        this.model.update(data, [ [ 'group_id', '=', group_id ) )];
        //删除缓存
        const cache_name = self.cache_name . group_id;
        Cache.delete(cache_name);

        const site_list = ( this.siteService ).field('site_id,initalled_addon').where([ [ 'group_id', '=', group_id ) )).select().toArray(];
        if (!!site_list)) {
            sort(data[ 'app' )];
            sort(group[ 'app' )];
            sort(data[ 'addon' )];
            sort(group[ 'addon' )];

            if (json_encode(data[ 'app' )) != json_encode(group[ 'app' )) || json_encode(data[ 'addon' )) != json_encode(group[ 'addon' ))) {
                foreach (site_list as site) {
                    this.siteAddonsChange(site, group, data);
                    Cache.tag(CoreSiteService.cache_tag_name . site[ 'site_id' )).clear(];

                    // 更新微页面数据
                    const diy_service = this.diyService;
                    diy_service.loadDiyData([ site_id: site[ 'site_id' ], main_app: data[ 'app' ), tag: 'update' );
  }
  }

  /**
   * edit
   * 对应 PHP: SiteGroupService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(group_id: any[], data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $group = $this->model->where([ [ 'group_id', '=', $group_id ] ])->findOrEmpty()->toArray();          //判断应用是否全部是有效的已安装应用         $this->checkAddon(arr...
const group = this.model.where([ [ 'group_id', '=', group_id ) )).findOrEmpty().toArray(];

        //判断应用是否全部是有效的已安装应用
        this.checkAddon(Object.assign(data[ 'app' ), data[ 'addon' ))];
        this.model.update(data, [ [ 'group_id', '=', group_id ) )];
        //删除缓存
        const cache_name = self.cache_name . group_id;
        Cache.delete(cache_name);

        const site_list = ( this.siteService ).field('site_id,initalled_addon').where([ [ 'group_id', '=', group_id ) )).select().toArray(];
        if (!!site_list)) {
            sort(data[ 'app' )];
            sort(group[ 'app' )];
            sort(data[ 'addon' )];
            sort(group[ 'addon' )];

            if (json_encode(data[ 'app' )) != json_encode(group[ 'app' )) || json_encode(data[ 'addon' )) != json_encode(group[ 'addon' ))) {
                foreach (site_list as site) {
                    this.siteAddonsChange(site, group, data);
                    Cache.tag(CoreSiteService.cache_tag_name . site[ 'site_id' )).clear(];

                    // 更新微页面数据
                    const diy_service = this.diyService;
                    diy_service.loadDiyData([ site_id: site[ 'site_id' ], main_app: data[ 'app' ), tag: 'update' );
  }
  }

  /**
   * siteAddonsChange
   * 对应 PHP: SiteGroupService_admin::siteAddonsChange()
   * 逻辑类型: undefined - undefined
   */
  async siteAddonsChange(site_info: any, old_group: any, new_group: any) {
    // 基于PHP真实逻辑: siteAddonsChange
    // PHP原文: $initalled_addon = $site_info[ 'initalled_addon' ];         if (empty($initalled_addon)) {             $initalled_addon = array_merge($old_group[ 'app...
const initalled_addon = site_info[ 'initalled_addon' ];
        if (!initalled_addon)) {
            const initalled_addon = Object.assign(old_group[ 'app' ), old_group[ 'addon' )];
  }

  /**
   * checkAddon
   * 对应 PHP: SiteGroupService_admin::checkAddon()
   * 逻辑类型: undefined - undefined
   */
  async checkAddon(group_roles: any) {
    // 基于PHP真实逻辑: checkAddon
    // PHP原文: $install_addon_list = ( new CoreAddonService() )->getInstallAddonList();         $install_addon_keys = array_column($install_addon_list, 'key');      ...
const install_addon_list = ( this.coreAddonService ).getInstallAddonList(];
        const install_addon_keys = array_column(install_addon_list, 'key');
        if (count(array_intersect(install_addon_keys, group_roles)) != count(group_roles)) throw new AdminBusinessException('SITE_GROUP_APP_NOT_EXIST');
        return true;
    }

    /**
     * 删除分组
     * @param int group_id
     * @return bool
     * @throws DbBusinessException
     */
    async del(int group_id)
    {
        const count = ( this.siteService ).where([ [ 'group_id', '=', group_id ) )).count(];
        if (count > 0) {
            throw new BusinessException('SITE_GROUP_IS_EXIST');
  }

  /**
   * del
   * 对应 PHP: SiteGroupService_admin::del()
   * 逻辑类型: undefined - undefined
   */
  async del(group_id: number) {
    // 基于PHP真实逻辑: del
    // PHP原文: $count = ( new Site() )->where([ [ 'group_id', '=', $group_id ] ])->count();         if ($count > 0) {             throw new CommonException('SITE_GRO...
const count = ( this.siteService ).where([ [ 'group_id', '=', group_id ) )).count(];
        if (count > 0) {
            throw new BusinessException('SITE_GROUP_IS_EXIST');
  }

  /**
   * getGroupAddon
   * 对应 PHP: SiteGroupService_admin::getGroupAddon()
   * 逻辑类型: undefined - undefined
   */
  async getGroupAddon(group_id: any) {
    // 基于PHP真实逻辑: getGroupAddon
    // PHP原文: $cache_name = self::$cache_name . $group_id;         return cache_remember(             $cache_name,             function() use ($group_id) {         ...
const cache_name = self.cache_name . group_id;
        return cache_remember(
            cache_name,
            function() use (group_id) {
                const group = this.model.findOrEmpty(group_id];
                const addon = [);
                if (!group.isEmpty()) {
                    const addon = Object.assign(group[ 'app' ), group[ 'addon' )];
                }
                return addon;
  }

  /**
   * addAllMenuGroup
   * 对应 PHP: SiteGroupService_admin::addAllMenuGroup()
   * 逻辑类型: undefined - undefined
   */
  async addAllMenuGroup() {
    // 基于PHP真实逻辑: addAllMenuGroup
    // PHP原文: //        $menus = (new SysMenu())->where([['app_type', '=', 'site']])->column("menu_key");         $data = [             'group_name' => "默认套餐",     ...
//        menus = this.sysMenuService.where([['app_type', '=', 'site'))).column("menu_key"];
        const data = [
            group_name: "默认套餐",
            group_desc: '',
            app: '',
            addon: []
        ];
        return this.add(data);
    }

    /**
     * 查询店铺套餐以及用户创建的站点数量
     * @param uid
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getUserSiteGroupAll(uid)
    {
        const field = 'group_id, group_name, group_desc, create_time, update_time, app';
        const list = this.model.field(field).select().toArray(];
        foreach (list as &item) {
            item[ 'site_num' ] = self.getUserSiteGroupSiteNum(uid, item[ 'group_id' )];
  }

  /**
   * getUserSiteGroupAll
   * 对应 PHP: SiteGroupService_admin::getUserSiteGroupAll()
   * 逻辑类型: undefined - undefined
   */
  async getUserSiteGroupAll(uid: any) {
    // 基于PHP真实逻辑: getUserSiteGroupAll
    // PHP原文: $field = 'group_id, group_name, group_desc, create_time, update_time, app';         $list = $this->model->field($field)->select()->toArray();         ...
const field = 'group_id, group_name, group_desc, create_time, update_time, app';
        const list = this.model.field(field).select().toArray(];
        foreach (list as &item) {
            item[ 'site_num' ] = self.getUserSiteGroupSiteNum(uid, item[ 'group_id' )];
  }

  /**
   * getUserSiteGroupSiteNum
   * 对应 PHP: SiteGroupService_admin::getUserSiteGroupSiteNum()
   * 逻辑类型: undefined - undefined
   */
  async getUserSiteGroupSiteNum(uid: any, group_id: any) {
    // 基于PHP真实逻辑: getUserSiteGroupSiteNum
    // PHP原文: return Db::name("sys_user_role")->alias('sur')             ->join('site s', 'sur.site_id = s.site_id')             ->where([                 [ 'sur.ui...
return Db.name("sys_user_role").alias('sur')
            .join('site s', 'sur.site_id = s.site_id')
            .where([
                [ 'sur.uid', '=', uid ],
                [ 'sur.is_admin', '=', 1 ],
                [ 's.group_id', '=', group_id )
            )).count(;
  }
  }
}
